#
# Copyright (c) 2021, 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#
require "../src/luce"
require "option_parser"

EXTENSION_SETS = {
  "none":            Luce::ExtensionSet::NONE,
  "CommonMark":      Luce::ExtensionSet::COMMON_MARK,
  "GitHubFlavoured": Luce::ExtensionSet::GITHUB_FLAVOURED,
  "GitHubWeb":       Luce::ExtensionSet::GITHUB_WEB,
}

extension_set = EXTENSION_SETS["CommonMark"]

parser = OptionParser.new
parser.banner = "Usage: #{PROGRAM_NAME} [options] [file]"
parser.on("-h", "--help", description: "Print help text and exit") do
  puts parser
  puts
  puts <<-USAGE
  Parse [file] as Markdown and print resulting HTML. If [file] is
  omitted, use STDIN as input.

  By default, CommonMark Markdown will be parsed. This can be changed with
  the --extension-set flag.
  USAGE
  exit 0
end
parser.on("-v", "--version", description: "Print version and exit") do
  puts Luce::VERSION
  exit 0
end
parser.on("--extension-set=SET", description: "Specify a set of extensions") do |set|
  if EXTENSION_SETS[set]?
    extension_set = EXTENSION_SETS[set]
  else
    STDERR.puts "Chosen extension '#{set}' not valid"
    puts "Choose one of [none, CommonMark, GitHubFlavoured, GitHubWeb]."
    exit(1)
  end
end
parser.missing_option do |flag|
  STDERR.puts "#{flag} is missing an option."
end
parser.invalid_option do |flag|
  STDERR.puts "#{flag} is not a valid option. Please use --help if you need"
  exit 1
end

parser.parse

if ARGV.size > 1
  puts parser
  puts
  puts <<-USAGE
  Parse [file] as Markdown and print resulting HTML. If [file] is
  omitted, use STDIN as input.

  By default, CommonMark Markdown will be parsed. THis can be changed with
  the --extension-set flag.
  USAGE
  exit(1)
end

if ARGV.size == 1
  # Read argument as a file path
  unless File.exists? ARGV.first
    STDERR.puts %{File "#{ARGV.first}" doesn't exist}
    exit(1)
  end
  input = File.read(ARGV.first)
  puts Luce.to_html(input, extension_set: extension_set)
  exit 0
end

# Read from STDIN
builder = String::Builder.new
while line = gets(chomp: false)
  builder << line
end
puts Luce.to_html(builder.to_s, extension_set: extension_set)
